<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Imagick;
use Intervention\Image\Exception\ImageException;
use Intervention\Image\ImageManagerStatic as Image;

class IndexController extends Controller
{
    private $image_directory;

    public function __construct()
    {
        // 初始化参数
        $this->image_directory = storage_path('app/public/remote_image_cache/');
        // 配置Intervention参数
        Image::configure(['driver' => 'gd']);
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return string
     *
     * @throws \ImagickException
     */
    public function index(Request $request)
    {
        try {
            // 获取请求参数
            $image_url = $request->has('url') ? $request->get('url') : '';
            $crop = $request->has('crop') ? $request->get('crop') : '';

            // 处理数据变量
            $image_path = $this->image_directory.sha1($image_url).'.jpg';

            // 判断图片是否缓存
            if (!file_exists($image_path)) {
                if (!$this->downImageByGD($image_url, $image_path)) {
                    return '缓存图片失败！';
                }
            }

            $image = Image::make($image_path);
            if ('y' === $crop || 'yes' === $crop) {
                $image_width = $request->has('width') ? $request->get('width') : 320;
                $image_height = $request->has('height') ? $request->get('height') : 240;
                $image->fit($image_width, $image_height);
            }

            header('Content-Type: image/jpg');
            echo $image->encode('jpg');
        } catch (ImageException $exception) {
            return '获取图片失败，错误原因是：<br>在文件'.$exception->getFile().'的第'.$exception->getLine().'行;<br>错误信息为'.$exception->getMessage();
        }
    }

    /**
     * 获取远程的图片到本地
     *
     * @param $url
     * @param $image_path
     *
     * @return bool
     */
    private function downImageByGD($url, $image_path)
    {
        if (!is_dir($this->image_directory)) {
            mkdir($this->image_directory, 0755);
        }

        $image_info = getimagesize($url);
        if (false === isset($image_info['mime'])) {
            return false;
        }

        switch ($image_info['mime']) {
            case 'image/png':
                $image = imagecreatefrompng($url);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($url);
                break;
            case 'image/jpeg':
                $image = imagecreatefromjpeg($url);
                break;
            case 'image/jpg':
                $image = imagecreatefromjpeg($url);
                break;
            case 'image/webp':
                $image = imagecreatefromwebp($url);
                break;
            default:
                return false;
                break;
        }

        if (isset($image_info[0]) && isset($image_info[1])) {
            $old_width = $image_info[0];
            $old_height = $image_info[1];

            if ($old_width > 750 || $old_height > 750) {
                if ($old_width >= $old_height) {
                    $new_width = 750;
                    $new_height = $old_height * $new_width / $old_width;
                } else {
                    $new_height = 750;
                    $new_width = $old_width * $new_height / $old_height;
                }

                // 根据缩放之后的宽高，生成指定大小的画布
                $new_image = imagecreatetruecolor((int) $new_width, (int) $new_height);
                // 将原图缩放到新图当中
                imagecopyresampled($new_image, $image, 0, 0, 0, 0, (int) $new_width, (int) $new_height, $old_width, $old_height);
                // 输出图像
                return imagejpeg($new_image, $image_path, 85);
            }
        }

        // 输出图像
        return imagejpeg($image, $image_path, 85);
    }

    /**
     * 获取远程的图片到本地
     *
     * @param $url
     * @param $image_path
     *
     * @return bool
     *
     * @throws \ImagickException
     */
    private function downImageByImagick($url, $image_path)
    {
        if (!is_dir($this->image_directory)) {
            mkdir($this->image_directory, 0755);
        }

        $image_info = getimagesize($url);
        if (false === isset($image_info['mime'])) {
            return false;
        }

        $imageMagic = new Imagick();
        // 读取图片
        $imageMagic->readImage($url);
        // 设置图片格式
        $imageMagic->setImageFormat('jpeg');

        if (isset($image_info[0]) && isset($image_info[1])) {
            $old_width = $image_info[0];
            $old_height = $image_info[1];

            if ($old_width > 750 || $old_height > 750) {
                if ($old_width >= $old_height) {
                    $new_width = 750;
                    $new_height = $old_height * $new_width / $old_width;
                } else {
                    $new_height = 750;
                    $new_width = $old_width * $new_height / $old_height;
                }

                // Crop image and thumb
                $imageMagic->cropThumbnailImage($new_width, $new_height);
            }
        }

        return $imageMagic->writeImage($image_path);
    }
}
